import 'dart:async';

typedef VoidCallback = void Function(int currentTime);

class CountDownTimeUtil {
  final int timeMax;
  final int interval;
  int _time = 60; //剩余秒数
  Timer? _timer;
  VoidCallback? _callback;

  int get currentTime => _time;

  bool get isFinish => _time == timeMax;

  ///[timeMax] 如60秒倒计时
  ///[interval] 如1秒会出发一次回调
  ///[callback] 倒计时出发回调 回传倒计时剩余秒数
  CountDownTimeUtil(this.timeMax, this.interval, VoidCallback callback) {
    _callback = callback;
    startCountDown();
  }

  void startCountDown() {
    cancel();
    _time = timeMax;
    _timer = Timer.periodic(Duration(seconds: interval), (time) {
      if (_timer?.tick == timeMax) {
        _time = 0;
        _timer?.cancel();
        _timer = null;
      } else {
        _time--;
      }
      _callback!(_time);
    });
  }

  void cancel() {
    if (_timer != null) {
      _timer?.cancel();
      _timer = null;
    }
  }
}
